from django.shortcuts import render, HttpResponse, redirect
from common.models import *
from django.db.models import Q
from django.contrib import auth
import xlrd
import re
from django.views import View
from django.utils.decorators import method_decorator
import json

from django.core import serializers


# Create your views here.
def index(request):
    return render(request, 'index.html')


def searchUser(request):
    keyword = request.GET.get('keyword')
    users = User.objects.filter(Q(name_pinyin=keyword) | Q(username__contains=keyword))
    users = serializers.serialize('json', users)
    return HttpResponse(users)


def checkLogin(func):
    def inner(request, *args, **kwargs):
        next = request.get_full_path()
        user = request.user
        if user.is_authenticated:
            return func(request, *args, **kwargs)
        else:
            return render(request, 'common/login.html', {'next': next})

    return inner


def login(request):
    if request.method == 'GET':
        return render(request, 'common/login.html')
    elif request.method == 'POST':
        error_message = ''
        next = request.POST.get('next')
        if next == '':
            next = '/'  # 如果next没有的话登录成功后就返回主页
        username = request.POST.get('username')
        password = request.POST.get('password')
        print(username, password)
        user = auth.authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                auth.login(request, user)
                return redirect(next)
        else:
            error_message = '用户名密码错误，请重新输入'
            return render(request, 'common/login.html',
                          {'error_message': error_message, 'next': next})


def logout(request):
    auth.logout(request)
    return redirect('/')


@checkLogin
def import_users(request):
    if request.method == 'GET':
        return render(request, 'common/import_users.html')

    elif request.method == 'POST':
        excel = request.FILES.get('excel')
        print(excel.name)
        if excel:
            # 判断excel后缀是否excel格式
            excel_suffix = excel.name.split('.')[-1]
            if excel_suffix not in ['xls', 'xlsx', 'csv']:
                return render(request, 'common/import_users.html', {'message': '仅支持excel格式的文件导入'})
            else:
                try:
                    wb = xlrd.open_workbook(filename=None, file_contents=excel.read())
                    sheet1 = wb.sheets()[0]
                    row = sheet1.nrows
                    existed_user = []  # 记录已存在的用户
                    import_user = []  # 记录导入成功的用户
                    # 第0行为表头,跳过
                    for i in range(1, row):
                        userinfo = {}
                        userprofile_info = {}
                        # 逐行取出数据
                        row_data = sheet1.row_values(i)
                        username = row_data[0]  # 表格中的第一列表示员工工号
                        if username:
                            if len(User.objects.filter(username=username)) > 0:
                                existed_user.append(username)  # 将已存在的用户添加到已存在列表，方便结果反馈
                                continue  # 中断当前循环，进入下一个循环
                            else:
                                userinfo['username'] = str(username).split('.')[0]
                        else:
                            continue
                        password = row_data[1]
                        if password:
                            userinfo['password'] = password
                        else:
                            userinfo['password'] = 'Lear2019'
                        name = row_data[2]
                        # name为必填项,否则继续其他
                        if name:
                            userinfo['first_name'] = name
                        gender = row_data[3]
                        if (gender == '男'):
                            userprofile_info['gender'] = 1
                        elif (gender == '女'):
                            userprofile_info['gender'] = 2
                        phone = row_data[4]
                        if phone:
                            userprofile_info['phone'] = phone
                        email = row_data[5]
                        if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$",
                                    email):
                            userinfo['email'] = email
                        department = row_data[6]
                        if len(Department.objects.filter(id=department)) > 0:
                            userprofile_info['department'] = Department.objects.get(id=department)
                        userinfo['is_active'] = True
                        user = User.objects.create_user(**userinfo)
                        userprofile_info['user'] = user
                        UserProfile.objects.create(**userprofile_info)

                        import_user.append(user)  # 将导入成功的用户存在成功列表方便结果反馈
                    return render(request, 'common/import_users.html',
                                  {
                                      'totalNum': row - 1,
                                      'existUser': existed_user,
                                      'importUser': import_user
                                  }
                                  )
                except Exception as e:
                    print('数据处理出错', e)
                    return render(request, 'common/import_users.html', {'message': '数据处理出错,请检查表格中的数据是否符合要求.'})
                return HttpResponse('success')
        else:
            return render(request, 'common/import_users.html', {'message': '请选择要导入的表格'})
